import type { Novel } from '@/api/types/novel'

/**
 * 平台跳转工具函数
 * 处理跳转到外部小说应用的各种逻辑
 */

// 平台配置映射
export interface PlatformConfig {
  name: string
  supportsWebJump: boolean
  supportsAppScheme: boolean
  appScheme?: string
  fallbackText?: string
  urlPatterns?: RegExp[]
  extractNovelId?: (url: string) => string | null
}

// 支持的平台配置
export const PLATFORM_CONFIGS: Record<string, PlatformConfig> = {
  qidian: {
    name: '起点中文网',
    supportsWebJump: true,
    supportsAppScheme: true,
    appScheme: 'qidian://book/detail?bookId={novelId}',
    fallbackText: '即将跳转到起点中文网',
    urlPatterns: [
      /qidian\.com\/book\/(\d+)/i,
      /book\.qidian\.com\/info\/(\d+)/i,
    ],
    extractNovelId: (url: string) => {
      const match = url.match(/qidian\.com\/book\/(\d+)/i)
        || url.match(/book\.qidian\.com\/info\/(\d+)/i)
      return match ? match[1] : null
    },
  },
  fanqie: {
    name: '番茄小说',
    supportsWebJump: true,
    supportsAppScheme: true,
    appScheme: 'fanqienovel://book/{novelId}',
    fallbackText: '即将跳转到番茄小说',
    urlPatterns: [
      /fanqienovel\.com\/page\/(\d+)/i,
      /novel\.reader\.tom\.com\/book\/(\d+)/i,
    ],
    extractNovelId: (url: string) => {
      const match = url.match(/fanqienovel\.com\/page\/(\d+)/i)
        || url.match(/novel\.reader\.tom\.com\/book\/(\d+)/i)
      return match ? match[1] : null
    },
  },
  zongheng: {
    name: '纵横中文网',
    supportsWebJump: true,
    supportsAppScheme: true,
    appScheme: 'zongheng://book/{novelId}',
    fallbackText: '即将跳转到纵横中文网',
    urlPatterns: [
      /zongheng\.com\/book\/(\d+)/i,
      /book\.zongheng\.com\/showchapter\/(\d+)/i,
    ],
    extractNovelId: (url: string) => {
      const match = url.match(/zongheng\.com\/book\/(\d+)/i)
        || url.match(/book\.zongheng\.com\/showchapter\/(\d+)/i)
      return match ? match[1] : null
    },
  },
  jjwxc: {
    name: '晋江文学城',
    supportsWebJump: true,
    supportsAppScheme: true,
    appScheme: 'jjwxc://novel/{novelId}',
    fallbackText: '即将跳转到晋江文学城',
    urlPatterns: [
      /jjwxc\.net\/onebook\.php\?novelid=(\d+)/i,
      /www\.jjwxc\.net\/onebook\.php\?novelid=(\d+)/i,
    ],
    extractNovelId: (url: string) => {
      const match = url.match(/novelid=(\d+)/i)
      return match ? match[1] : null
    },
  },
}

/**
 * 从URL中提取小说ID
 */
export function extractNovelIdFromUrl(url: string, platform: string): string | null {
  const config = PLATFORM_CONFIGS[platform]
  if (!config || !config.extractNovelId) {
    return null
  }

  return config.extractNovelId(url)
}

/**
 * 生成App跳转的URL Scheme
 */
export function generateAppScheme(novel: Novel): string | null {
  const { platform, originalUrl } = novel
  const config = PLATFORM_CONFIGS[platform!]

  if (!config || !config.supportsAppScheme || !config.appScheme || !originalUrl) {
    return null
  }

  const novelId = extractNovelIdFromUrl(originalUrl, platform!)
  if (!novelId) {
    return null
  }

  return config.appScheme.replace('{novelId}', novelId)
}

/**
 * 检查小说是否支持外部跳转
 */
export function canJumpToExternal(novel: Novel): boolean {
  return !!(novel.platform && novel.originalUrl && PLATFORM_CONFIGS[novel.platform])
}

/**
 * 检查是否支持App跳转
 */
export function canJumpToApp(novel: Novel): boolean {
  return !!(canJumpToExternal(novel) && generateAppScheme(novel))
}

/**
 * 获取平台配置
 */
export function getPlatformConfig(platform: string): PlatformConfig | null {
  return PLATFORM_CONFIGS[platform] || null
}

/**
 * H5平台跳转处理
 */
export function jumpToExternalWeb(url: string): Promise<void> {
  return new Promise((resolve, reject) => {
    try {
      // H5平台直接使用 window.open
      const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
      if (newWindow) {
        resolve()
      }
      else {
        // 如果弹窗被阻止，尝试直接跳转
        window.location.href = url
        resolve()
      }
    }
    catch (error) {
      reject(error)
    }
  })
}

/**
 * 微信小程序平台跳转处理
 */
export function jumpToExternalMiniProgram(url: string): Promise<void> {
  return new Promise((resolve, reject) => {
    try {
      // 微信小程序复制链接到剪贴板并提示用户
      uni.setClipboardData({
        data: url,
        success: () => {
          uni.showModal({
            title: '跳转提示',
            content: '链接已复制到剪贴板，请在浏览器中打开访问原小说页面',
            showCancel: true,
            confirmText: '知道了',
            cancelText: '取消',
            success: (res) => {
              if (res.confirm || res.cancel) {
                resolve()
              }
              else {
                reject(new Error('用户取消操作'))
              }
            },
            fail: () => reject(new Error('显示提示失败')),
          })
        },
        fail: () => reject(new Error('复制链接失败')),
      })
    }
    catch (error) {
      reject(error)
    }
  })
}

/**
 * App平台跳转处理（优先使用URL Scheme）
 */
export function jumpToExternalApp(novel: Novel): Promise<void> {
  return new Promise((resolve, reject) => {
    try {
      // #ifdef APP-PLUS
      // @ts-expect-error - uniapp 的 plus 对象在 App 平台可用
      if (typeof plus !== 'undefined' && plus.runtime) {
        // 优先尝试URL Scheme跳转到App
        const appScheme = generateAppScheme(novel)

        if (appScheme) {
          console.log('尝试使用URL Scheme跳转:', appScheme)
          console.log('appScheme类型:', typeof appScheme)
          // @ts-expect-error - plus.runtime.openURL 的类型定义
          plus.runtime.openURL(appScheme, (result: any) => {
            // 根据起点App文档，result.code === -1 表示未安装应用
            console.log('openURL 回调结果:', result)
            if (result && result.code === -1) {
              console.log('未安装对应App，尝试网页跳转')
              // App未安装，尝试网页跳转
              jumpToExternalAppWeb(novel.originalUrl!).then(resolve).catch(reject)
            }
            else if (result && result.code === 0) {
              // 成功跳转
              console.log('URL Scheme跳转成功')
              resolve()
            }
            else {
              console.log('URL Scheme跳转失败，尝试网页跳转:', result)
              // 其他错误，尝试网页跳转
              jumpToExternalAppWeb(novel.originalUrl!).then(resolve).catch(reject)
            }
          })
        }
        else {
          // 不支持URL Scheme，直接使用网页跳转
          jumpToExternalAppWeb(novel.originalUrl!).then(resolve).catch(reject)
        }
      }
      else {
        reject(new Error('App runtime 不可用'))
      }
      // #endif

      // #ifndef APP-PLUS
      // 非 App 平台使用 H5 方式
      jumpToExternalWeb(novel.originalUrl!).then(resolve).catch(reject)
      // #endif
    }
    catch (error) {
      reject(error)
    }
  })
}

/**
 * App平台网页跳转处理
 */
export function jumpToExternalAppWeb(url: string): Promise<void> {
  return new Promise((resolve, reject) => {
    try {
      // #ifdef APP-PLUS
      // @ts-expect-error - uniapp 的 plus 对象在 App 平台可用
      if (typeof plus !== 'undefined' && plus.runtime) {
        // @ts-expect-error - plus.runtime.openURL 的类型定义
        plus.runtime.openURL(url, (error: any) => {
          if (error) {
            // 如果 App 跳转失败，尝试复制链接
            uni.setClipboardData({
              data: url,
              success: () => {
                uni.showModal({
                  title: '跳转提示',
                  content: '无法直接打开链接，链接已复制到剪贴板，请在浏览器中粘贴访问',
                  showCancel: false,
                  success: () => resolve(),
                  fail: () => reject(new Error('复制链接失败')),
                })
              },
              fail: () => reject(new Error('无法打开链接且复制失败')),
            })
          }
          else {
            resolve()
          }
        })
      }
      else {
        reject(new Error('App runtime 不可用'))
      }
      // #endif
    }
    catch (error) {
      reject(error)
    }
  })
}

/**
 * 主要跳转函数
 */
export async function jumpToExternalNovel(novel: Novel): Promise<void> {
  // 检查是否支持外部跳转
  if (!canJumpToExternal(novel)) {
    throw new Error('该小说不支持外部跳转')
  }

  const { platform, originalUrl } = novel
  const config = getPlatformConfig(platform!)

  if (!config) {
    throw new Error('不支持的小说平台')
  }

  // 检查当前平台
  const currentPlatform = getPlatform()

  try {
    switch (currentPlatform) {
      case 'h5':
        await jumpToExternalWeb(originalUrl!)
        break
      case 'mp-weixin':
        await jumpToExternalMiniProgram(originalUrl!)
        break
      case 'app':
        await jumpToExternalApp(novel)
        break
      default:
        // 默认使用 H5 方式
        await jumpToExternalWeb(originalUrl!)
        break
    }
  }
  catch (error) {
    console.error('跳转失败:', error)
    throw new Error(`跳转到${config.name}失败: ${error instanceof Error ? error.message : '未知错误'}`)
  }
}

/**
 * 获取当前运行平台
 */
function getPlatform(): string {
  // #ifdef H5
  return 'h5'
  // #endif

  // #ifdef MP-WEIXIN
  return 'mp-weixin'
  // #endif

  // #ifdef APP-PLUS
  return 'app'
  // #endif

  // 默认返回 h5
  return 'h5'
}

/**
 * 显示跳转确认对话框
 */
export function showJumpConfirm(config: PlatformConfig): Promise<boolean> {
  return new Promise((resolve) => {
    uni.showModal({
      title: '跳转确认',
      content: `即将跳转到${config.name}阅读，是否继续？`,
      success: (res) => {
        resolve(res.confirm)
      },
      fail: () => {
        resolve(false)
      },
    })
  })
}

/**
 * 测试URL Scheme生成（仅用于开发调试）
 */
export function testUrlSchemeGeneration(novel: Novel): void {
  if (!novel.platform || !novel.originalUrl) {
    console.log('❌ 小说数据不完整，无法测试')
    return
  }

  const config = PLATFORM_CONFIGS[novel.platform]
  if (!config) {
    console.log('❌ 不支持的平台:', novel.platform)
    return
  }

  console.log('📱 测试URL Scheme生成:')
  console.log('平台:', config.name)
  console.log('原始URL:', novel.originalUrl)

  const novelId = extractNovelIdFromUrl(novel.originalUrl, novel.platform)
  console.log('提取的小说ID:', novelId)

  const appScheme = generateAppScheme(novel)
  console.log('生成的URL Scheme:', appScheme)

  if (appScheme) {
    console.log('✅ URL Scheme生成成功')
  }
  else {
    console.log('❌ URL Scheme生成失败')
  }
}
